package com.landas

import org.gradle.api.Plugin
import org.gradle.api.internal.project.ProjectInternal

/**
 * 将 {@link MybatisGeneratorTask} 封装为 Gradle Plugin
 *
 * @author Maomao Chen
 * @author landas
 * @version 1.0.0
 * @since 1.0.0
 */
class MybatisGeneratorPlugin implements Plugin<ProjectInternal> {

    @Override
    void apply(ProjectInternal project) {
        project.logger.info "Configuring Mybatis Generator for project: $project.name"
        // 向 gradle 注册MybatisGeneratorTask
        MybatisGeneratorTask task = project.tasks.register("runGenerator", MybatisGeneratorTask).get()
        project.configurations.create("mybatisGeneratorConf").with {
            description = "Config your customised mybatis generation here"
        }
        // 加载自定义任务配置
        project.extensions.create("mybatisGeneratorConf", MybatisGeneratorExtension)
        task.conventionMapping.with {
            configurationClasspath = {
                def config = project.configurations['mybatisGeneratorConf']
                if (config.dependencies.empty) {
                    project.dependencies {
                        mybatisGeneratorConf 'org.mybatis.generator:mybatis-generator-core:1.3.5'
                        mybatisGeneratorConf 'mysql:mysql-connector-java:5.1.47'
                    }
                }
                config
            }
            configFile = {project.mybatisGeneratorConf.configFile}
            overwrite = {project.mybatisGeneratorConf.overwrite}
            verbose = {project.mybatisGeneratorConf.verbose}
            targetDir = {project.mybatisGeneratorConf.targetDir}
            contextIds = {project.mybatisGeneratorConf.contextIds}
            fullyQualifiedTableNames = {project.mybatisGeneratorConf.fullyQualifiedTableNames}
        }
    }
}
